import { DestroyRef, Directive, EventEmitter, Input, OnInit, Output, inject } from "@angular/core";
import { takeUntilDestroyed } from "@angular/core/rxjs-interop";
import { NgModel } from "@angular/forms";
import { NzSafeAny } from "ng-zorro-antd/core/types";
import { debounce, distinctUntilChanged, skip, timer } from "rxjs";

@Directive({
	selector: '[appModelDelayChange]',
})
export class ModelDelayDirective implements OnInit {
	readonly destroyRef = inject(DestroyRef);

	@Input() delayTime = 100;
	/** Emit event when model has changed. */
	@Output() modelDelayChange = new EventEmitter<NzSafeAny>();

	constructor(private ngModel: NgModel) { }

	ngOnInit(): void {
		this.ngModel.control.valueChanges
			.pipe(
				skip(1),
				debounce(() => timer(this.delayTime)),
				distinctUntilChanged(
					(prev, curr) => {
						return prev == curr;
					}
				),
				takeUntilDestroyed(this.destroyRef)
			)
			.subscribe(value => this.modelDelayChange.emit(value));
	}
}